package com.zhouyer.study.classloader;

import java.io.*;

/**
 * 自定义类加载器
 *
 * @author zhouyao
 * @version 1.0
 * @date 2021/9/16 8:50 上午
 */
public class MyClassLoader extends ClassLoader {

    private static final String CLASS_FILE_EXT = ".class";

    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        // 获取待加载的全限定类名
        String className = name.substring(name.lastIndexOf("/") + 1);
        // 将.转成/
        String myClassPath = name.replace(".", "/") + CLASS_FILE_EXT;
        System.out.println("=======> MyClassPath:" + myClassPath);
        byte[] cLassBytes = fileToByteArray(myClassPath);
        return super.defineClass(className, cLassBytes, 0, cLassBytes.length);
    }

    private byte[] fileToByteArray(String path) {
        byte[] data = null;
        try (InputStream inputStream = new BufferedInputStream(new FileInputStream(new File(path)));
             ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
            // 缓冲区大小
            int bufferLen = 1024;
            byte[] buffer = new byte[bufferLen];
            // 读取长度
            int len = -1;
            while ((len = inputStream.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            data = baos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }
}
